
/* -----------------
* brief 
* 1. this is code gen by tools
*/

package service

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"github.com/mjiulee/lego"
	"saas_sys_base/common"
	"saas_sys_base/sysconfig"
	"time"
)
import . "saas_sys_base/modules/user/models"

type AppTenantRelService struct {
	// add your model here
	tbAppTenantRel AppTenantRel
}


func (t* AppTenantRelService)ListAppTenantRel(keyword string,page,psize int) ([]map[string]string, int64, error) {
	// 业务查询
	queryMap := map[string]interface{}{
		"table":  map[string]string{"table": "tb_app_tenant_rel", "alias": "t1"},
		"fields": []string{"t1.*"},
		"join": []map[string]string{
			// map[string]string{"table": "tb_xx as t2", "on": "t2.xid = t1.id"},
		},
		"where": []lego.QMapWhereField{
			//{"t1.if_del", "=", 0, "AND", false},
		},
		"search": map[string]string{
			//"t1.id": req.Keyword,
		},
		"orders": []string{"t1.id asc"},
		"page": map[string]int{
			"page":  page,
			"psize": psize,
		},
	}
	return lego.QueryListByMap(queryMap)
}

/* 根据id获取记录
 * -----------------
 */
func (t* AppTenantRelService) GetAppTenantRelById(id int64) *AppTenantRel {
	return t.tbAppTenantRel.RecodeById(id)
}

/* 添加
 * -----------------
 */
func (t* AppTenantRelService) SaveAppTenantRel(item2add *AppTenantRel) bool {
	return t.tbAppTenantRel.AddRecode(item2add)
}

/* 删除(硬删除)*/
func (t* AppTenantRelService) DelAppTenantRelById(id int64) bool {
	return t.tbAppTenantRel.DelRecodeById(id)
}

/* 更新
 * -----------------*/
func (t* AppTenantRelService) UpdateAppTenantRel(rc *AppTenantRel) bool {
	return t.tbAppTenantRel.UpdateRecode(rc)
}

func (t *AppTenantRelService) userLogin(who common.Who/*MiniAppId int64, tid int64, sysUid int64*/) (relUser *AppTenantRel, tokenString string, err error) {

	rel := t.tbAppTenantRel.RecodeByWho(who /*MiniAppId, tid, sysUid*/)
	if rel == nil {
		item2add := new(AppTenantRel)
		item2add.MiniAppId = who.GetMiniAppId()
		item2add.TenantId = who.GetTenantId()
		item2add.Uid = who.GetUid()
		if false == t.tbAppTenantRel.AddRecode(item2add) {
			return nil, "", errors.New("UserLogin Failed in AppTenantRelService UserLogin")
		}
		rel = item2add
	}

	/*PosId := PosId{
		MiniAppId:MiniAppId,
		Tid:tid,
		SysUid:sysUid,
	}*/
	RelId := rel.Id
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, UserRelCustomClaims{
		RelId,
		jwt.StandardClaims{ExpiresAt: time.Now().Add(TOKEN_EXPIRE_DURATION).Unix()},
	})

	/*token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"rel_id": rel.Id,
		"exp": time.Now().Add(time.Hour * 24).Unix(),
		//"exp": time.Now().Add(time.Minute * 3).Unix(),
	})*/

	tokenString, err = token.SignedString([]byte(sysconfig.SecretKey()))
	if err != nil {
		return nil, "", errors.New("token生成失败")
	}

	return rel, tokenString, nil
}
